package com.gin.no_gay_alliance.listener;

import android.content.DialogInterface;
import android.util.Log;
import android.view.MenuItem;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;

import com.gin.jackson.utils.JacksonUtils;
import com.gin.nga.callback.JsonCallback;
import com.gin.nga.client.NgaClient;
import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.params.nuke.ReportParam;
import com.gin.nga.params.nuke.base.NukeEditHistoryParam;
import com.gin.nga.params.nuke.notice.NoticeEnableParam;
import com.gin.nga.response.body.BaseMessageBody;
import com.gin.nga.response.body.nuke.EditHistoryBody;
import com.gin.nga.response.field.EditHistory;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.BaseBindingActivity;
import com.gin.no_gay_alliance.activity.SourceCodeActivity;
import com.gin.no_gay_alliance.activity.TopicListActivity;
import com.gin.no_gay_alliance.activity.TopicReadActivity;
import com.gin.no_gay_alliance.adpter.EditHistoryAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.BaseMessageCallback;
import com.gin.no_gay_alliance.database.entity.ReportingRecord;
import com.gin.no_gay_alliance.databinding.DialogRecyclerViewEditHistoryBinding;
import com.gin.no_gay_alliance.enums.MessageWhat;
import com.gin.no_gay_alliance.fragment.user.tab.UserItemTabFragment;
import com.gin.no_gay_alliance.param.ItemParam;
import com.gin.no_gay_alliance.param.PreparePostParam;
import com.gin.no_gay_alliance.param.TopicListParam;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.CopyUtils;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.MyHandler;
import com.gin.no_gay_alliance.viewmodel.ReplyItem;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 回复的工具按钮点击响应
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/19 12:28
 **/
public class ReplyItemPopupOnMenuItemClickListener extends PopupOnMenuItemClickListener<ReplyItem> {
    public static final String TAG = ReplyItemPopupOnMenuItemClickListener.class.getSimpleName();
    @NonNull
    final FragmentActivity activity;
    MyHandler handler;
    BaseMessageCallback baseMessageCallback;
    long forumId;

    public ReplyItemPopupOnMenuItemClickListener(@NonNull FragmentActivity activity) {
        this.activity = activity;
        if (activity instanceof BaseBindingActivity) {
            this.handler = ((BaseBindingActivity<?>) activity).getHandler();
            baseMessageCallback = new BaseMessageCallback(this.handler);
        }
    }

    /**
     * 菜单项目的点击事件处理
     *
     * @param item     数据项目
     * @param menuItem 菜单项目
     * @param itemId   菜单项目id
     * @return boolean
     */
    @Override
    protected boolean onMenuItemClick(ReplyItem item, MenuItem menuItem, int itemId) {
        if (itemId == R.id.tv_comment) {
            Log.d(TAG, "评论");
            PreparePostParam p = new PreparePostParam(PreparePostParam.Action.REPLY, item.topicId, item.replyId);
            p.isComment = true;
            handler.sendMessage(MessageWhat.START_ACTIVITY_POST_ACTIVITY, p);
            return true;
        }
        if (itemId == R.id.tv_edit) {
            Log.d(TAG, "编辑");
            PreparePostParam p = new PreparePostParam(PreparePostParam.Action.MODIFY, item.topicId, item.replyId);
            handler.sendMessage(MessageWhat.START_ACTIVITY_POST_ACTIVITY, p);
            return true;
        }
        if (itemId == R.id.tv_notify_off) {
            Log.d(TAG, "关闭提醒");
            NgaClient client = MyApplication.getClient();
            NoticeEnableParam param = new NoticeEnableParam(item.topicId, item.replyId, false);
            NukeApi.noticeEnable(client, param).async(baseMessageCallback);
            return true;
        }
        if (itemId == R.id.tv_notify_on) {
            Log.d(TAG, "开启提醒");
            NgaClient client = MyApplication.getClient();
            NoticeEnableParam param = new NoticeEnableParam(item.topicId, item.replyId, true);
            NukeApi.noticeEnable(client, param).async(baseMessageCallback);
            return true;
        }
        if (itemId == R.id.tv_report) {
            Log.d(TAG, "举报");
            EditText editText = new EditText(activity);
            editText.setHint("不要仅仅因为意见不同而举报");


            AlertDialogUtils.showConfirm(activity, "举报", "请填写举报理由", editText, (d, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    String reason = editText.getText().toString();

                    NgaClient client = MyApplication.getClient();
                    ReportParam param = new ReportParam(item.topicId, item.replyId, reason);
                    NukeApi.report(client, param).async(new BaseMessageCallback(handler) {
                        @Override
                        public void onSuccess(BaseMessageBody body) {
                            super.onSuccess(body);
                            // 举报记录
                            ReportingRecord reportingRecord = new ReportingRecord(item, reason);
                            // 保存举报记录
                            MyApplication.app.ngaDatabase.reportingRecordDao().add(reportingRecord);
                        }
                    });
                }
            });

            //获取焦点
            editText.requestFocus();
            handler.postDelayed(() -> InputMethodManagerUtils.show(editText), 200);

            return true;
        }
        if (itemId == R.id.tv_gift) {
            Log.d(TAG, "礼物");
            UserItemTabFragment.showDialog(activity, new ItemParam(item.topicId, item.replyId));
            return true;
        }
        if (itemId == R.id.tv_favor) {
            MyApplication.app.managerFactory.getFavorManager().topicAddDialog(activity,
                    handler,
                    item.topicId,
                    item.replyId,
                    data -> handler.toast(data.getMessage()));
            return true;
        }
        if (itemId == R.id.tv_source_code) {
            SourceCodeActivity.startActivity(activity, item.content);
            return true;
        }

        // 分享功能
        if (itemId == R.id.menu_item_copy_link) {
            CopyUtils.copyLink(activity, item.topicId, item.replyId);
            return true;
        }
        if (itemId == R.id.menu_item_copy_bbs_code) {
            CopyUtils.copyBbsCode(activity, item.topicId, item.replyId, item.title, item.username);
            return true;
        }

        if (itemId == R.id.watch_only) {
            // 只看TA
            TopicReadActivity.startActivity(activity, item.topicId, item.authorUid, item.username);
            return true;
        }
        // todo 编辑历史
        if (itemId == R.id.tv_edit_history) {
            // 点击查询编辑历史，如果报错弹出信息

            NukeEditHistoryParam param = new NukeEditHistoryParam(item.topicId, item.replyId, 1);
            NukeApi.editHistory(MyApplication.getClient(), param).async(new JsonCallback<EditHistoryBody>() {
                @Override
                public void onSuccess(EditHistoryBody body) {
                    LinkedHashMap<Integer, EditHistory> data = body.getData();
                    if (data.isEmpty()) {
                        handler.toast("无编辑历史");
                        return;
                    }
                    //todo 有编辑历史，打开弹窗选择
                    ArrayList<EditHistory> editHistories = new ArrayList<>(data.values());
                    JacksonUtils.printPretty(editHistories);

                    handler.post(() -> {
                        DialogRecyclerViewEditHistoryBinding b = MyApplication.app.managerFactory.getViewBindingManager().getDialogView(DialogRecyclerViewEditHistoryBinding.class, activity);

                        b.recyclerView.setAdapter(new EditHistoryAdapter(activity, editHistories));

                        AlertDialog dialog = AlertDialogUtils.showConfirm(activity, "编辑历史", null, b.getRoot(), null);
                    });
                }

                /**
                 * 处理异常
                 *
                 * @param e 异常
                 */
                @Override
                public void handleException(NgaException e) {
//                    super.handleException(e);
                    if (e instanceof NgaClientException) {
                        Map<Integer, String> reason = ((NgaClientException) e).getReason();
                        handler.toastLong(reason.get(0));
                    } else {
                        e.printStackTrace();
                    }
                }
            });

            return true;
        }

        // 点击其他按钮时打开活动
        TopicListParam param = new TopicListParam();
        param.type = TopicListParam.Type.USER_SEARCH;
        param.authorUid = item.authorUid;
        if (itemId == R.id.user_topic) {
            // 直接发送
            param.title = item.username + " 发布的主题";
            TopicListActivity.startActivity(activity, param);
            return true;
        }
        if (itemId == R.id.user_reply) {
            param.searchReply = true;
            param.title = item.username + " 发布的回复";
            TopicListActivity.startActivity(activity, param);
            return true;
        }
        if (itemId == R.id.user_topic_forum) {
            param.forumId = String.valueOf(forumId);
            // 直接发送
            param.title = item.username + " 的本版主题";
            TopicListActivity.startActivity(activity, param);
            return true;
        }
        if (itemId == R.id.user_topic_forum_recommend) {
            param.forumId = String.valueOf(forumId);
            param.recommendOnly = true;
            param.title = item.username + " 的本版精华";
            TopicListActivity.startActivity(activity, param);
            return true;
        }
        if (itemId == R.id.user_reply_forum) {
            param.forumId = String.valueOf(forumId);
            param.searchReply = true;
            param.title = item.username + " 的本版回复";
            TopicListActivity.startActivity(activity, param);
            return true;
        }
        return false;
    }

    public void setForumId(long forumId) {
        this.forumId = forumId;
    }

    public void setHandler(MyHandler handler) {
        this.handler = handler;
    }
}
